package com.mantru.iotpot.setting

import android.app.Application
import android.content.Context
import android.icu.text.SimpleDateFormat
import android.util.Log
import androidx.databinding.ObservableField
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.mantru.iotpot.ApplicationClass
import com.mantru.iotpot.Util.DownloadUtil
import com.mantru.iotpot.Util.MotherboardUtil
import com.mantru.iotpot.eventbus.EventMessage
import com.mantru.iotpot.eventbus.EventMessage.MSG_ID_OnHttpData_APP
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject
import java.text.ParseException
import java.util.Locale

class UpgradeAppViewModel (application: Application) : AndroidViewModel(application) {

    private val applicationClass: ApplicationClass = application as ApplicationClass
    private val context = application.applicationContext

    //升级参数
    var fileUrl = ObservableField<String>()
    var downloadUtil = DownloadUtil()
    private val okHttpClient = OkHttpClient()
    //文件数据
    val _fileSize = MutableLiveData<Long?>()
    val fileSize: LiveData<Long?> = _fileSize
    val _lastModified = MutableLiveData<String?>()
    val lastModified: LiveData<String?> = _lastModified
    var needUpgradeTip = false
    // 进度 LiveData
    val _downloadResult = MutableLiveData<Boolean>()
    val downloadResult: LiveData<Boolean> = _downloadResult
    val _downloadProgress = MutableLiveData<Int>()
    val downloadProgress: LiveData<Int> = _downloadProgress
    // 文件路径 LiveData
    val downloadFilePath = MutableLiveData<String>()
    // 错误 LiveData
    val downloadError = MutableLiveData<Exception>()

    init {
        //在这里实现主板设置的初始化
        MotherboardUtil.initMotherboard(context)
        // 注册EventBus
        EventBus.getDefault().register(this)
    }

    override fun onCleared() {
        super.onCleared()
        // 取消注册EventBus
        EventBus.getDefault().unregister(this)
    }

    //获取升级版本数据
    fun getUpgradeValue(){
        val map: MutableMap<String, Any> = HashMap()
        getHttpValue("GetAppUpgradeUrl", map)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventBusMessage(event: EventMessage) {
        // 在这里处理EventBus事件
        when (event.id) {
            MSG_ID_OnHttpData_APP -> {//检查APP是否有版本更新
                val json = event.message
                if (!json.isNullOrEmpty()) {
                    try {
                        val jsonObject = JSONObject(json)
                        val success = jsonObject.getBoolean("success")
                        if (success) {
                            val upgradeData = jsonObject.getJSONObject("upgrade_data")
                            val needUpgrade = (upgradeData.get("is_need_upgrade").toString() == "1")
                            if (needUpgrade) {
                                fileUrl.set(upgradeData.getString("file_url"))
                                if ( needUpgradeTip ){
                                    _downloadResult.postValue(true)
                                    startDownload(fileUrl.get().toString())
                                } else {
                                    viewModelScope.launch {
                                        getFileInformation(fileUrl.get().toString())
                                    }
                                }
                            }
                        } else {
                            Log.e("---GetAppUpgradeUrl", "API返回success=false")
                            _downloadResult.postValue(false)
                        }
                    } catch (e: Exception) {
                        Log.e("---GetAppUpgradeUrl:", e.toString())
                        _downloadResult.postValue(false)
                    }
                } else {
                    Log.e("---GetAppUpgradeUrl", "返回的JSON数据为空")
                    _downloadResult.postValue(false)
                }
            }
        }
    }

    // 开始下载
    private fun startDownload(url: String) {

        downloadUtil = DownloadUtil()
        downloadUtil.downloadApk(context, url, object : DownloadUtil.DownloadProgressCallback {
            override fun onProgressUpdate(progress: Int) {
                // 更新进度
                _downloadProgress.postValue(progress)
            }

            override fun onDownloadComplete(filePath: String) {
                // 下载完成，更新文件路径
                downloadFilePath.postValue(filePath)
                // 安装 APK
                downloadUtil.installApk(context, filePath)
            }

            override fun onError(e: Exception) {
                // 错误处理
                downloadError.postValue(e)
            }
        })
    }

    //取消下载apk
    fun cancelDownload(){
        downloadUtil.cancel()
    }

    //获取网络数据
    fun getHttpValue(api: String, map: Map<String, Any>){
        when ( api ){
            "GetAppUpgradeUrl" ->{//获取升级数据
                applicationClass.GetAppUpgradeUrl()
            }
        }
    }

    private suspend fun getFileInformation(url: String) {
        withContext(Dispatchers.IO) {
            val request = Request.Builder()
                .url(url)
                .head()
                .build()

            okHttpClient.newCall(request).execute().use { response ->
                if (response.isSuccessful) {
                    val contentLength = response.header("Content-Length")?.toLongOrNull()
                    val lastModifiedHeader = response.header("Last-Modified")

//                    val fileSizeInMB = contentLength?.div(1024 * 1024.0)
//                    val fileSizeInMBFormatted = fileSizeInMB?.let { String.format("%.2f", it) }

                    // 解析和格式化 Last-Modified 头部信息
                    val formattedLastModified = try {
                        val inputFormat = SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US)
                        val outputFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
                        val date = inputFormat.parse(lastModifiedHeader.orEmpty())
                        date?.let { outputFormat.format(it) }
                    } catch (e: ParseException) {
                        null
                    }

                    _fileSize.postValue(contentLength)
                    _lastModified.postValue(formattedLastModified)
                } else {
                    Log.e("---Error", "Failed to get file information. Status Code: ${response.code}")
                }
            }
        }
    }
}